package com.piece.core.oauth.filter;

import com.piece.core.web.authority.token.CompositeAuthorizationGranter;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.util.basic.I18nUtil;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.List;

/**
 * 默认登录过滤器
 */
public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private final boolean POST_ONLY = true;
    private final List<CompositeAuthorizationGranter> compositeAuthorizations;

    public AuthenticationFilter(String processesUrl, List<CompositeAuthorizationGranter> compositeAuthorizations) {
        super(new AntPathRequestMatcher(processesUrl, "POST"));
        this.compositeAuthorizations = compositeAuthorizations;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (POST_ONLY && !"POST".equalsIgnoreCase(request.getMethod())) {
            throw new AuthenticationServiceException(I18nUtil.message(ExceptionConstants.METHOD, request.getMethod()));
        } else {
            Authentication authentication;
            Iterator var3 = this.compositeAuthorizations.iterator();
            do {
                if (!var3.hasNext()) {
                    return null;
                }

                CompositeAuthorizationGranter token = (CompositeAuthorizationGranter) var3.next();
                authentication = token.get(request);
            } while(null == authentication);

            return this.getAuthenticationManager().authenticate(authentication);
        }
    }
}
